﻿using System.Collections.Generic;
using System.Data;
using System.Data.OleDb;
using System.Windows;
using SHomeWorkshop.LunarPresentation.Dialogs;

namespace SHomeWorkshop.LunarPresentation.Commands
{
    public partial class Command
    {
        #region 旧的查找方法，涉及主界面。
        /// <summary>
        /// 参数用于重启快捷键（使主窗口获取焦点）。
        /// </summary>
        /// <param name="window"></param>
        //public static void Find(MainWindow window)
        //{
        //    if (Globals.selectedEditor == null) return;

        //    Dialogs.InputWindow iw = new Dialogs.InputWindow(window, "请输入查找关键词，以便在当前文档中搜索：", "");
        //    if (iw.ShowDialog() != true || iw.InputedText.Length < 1)
        //    {
        //        window.Focus();
        //        Globals.SwitchInputMethod(false);
        //        return;
        //    }

        //    if (window.toolTab.SelectedItem != window.tiFindInDocument)
        //    {
        //        window.toolTab.SelectedItem = window.tiFindInDocument;
        //    }

        //    window.Focus();
        //    Globals.SwitchInputMethod(false);

        //    string keyword = iw.InputedText;

        //    // 找出所有符合条件的文本块，并添加到右侧列表框中。
        //    if (keyword.Length <= 0) return;

        //    List<Expressions.BaseText> resultList = new List<Expressions.BaseText>();
        //    FindBaseTextInExpression(resultList, Globals.selectedEditor.RootPanel, keyword);

        //    window.spFindResult.Children.Clear();
        //    foreach (UIElement ue in resultList)
        //    {
        //        Expressions.BaseText bt = ue as Expressions.BaseText;

        //        if(bt != null)
        //        {
        //            window.spFindResult.Children.Add(new FindTextBlock(bt));
        //        }
        //    }

        //    if (window.gcAssist.ActualWidth < 140)
        //    {
        //        window.gcAssist.Width = new GridLength(300);
        //        window.toolTab.Visibility = Visibility.Visible;
        //    }
        //}
        #endregion

        public static void Find()
        {
            FindDialog findDialog = new FindDialog() { Owner = Globals.MainWindow };
            findDialog.ShowDialog();
        }

        public static void FindBaseTextInExpression(List<Expressions.BaseText> resultList,
            Expressions.Expression ex, string keyword)
        {
            if (ex == null || resultList == null) return;

            if (ex is Expressions.SubPanel)
            {
                Expressions.SubPanel sPanel = ex as Expressions.SubPanel;
                for (int i = 0; i < sPanel.BasePanel.Children.Count; i++)
                {
                    Expressions.Expression exInPanel = sPanel.BasePanel.Children[i] as Expressions.Expression;

                    FindBaseTextInExpression(resultList, exInPanel, keyword);
                }
            }
            else
            {
                if (ex is Expressions.BaseText)
                {
                    Expressions.BaseText bt = ex as Expressions.BaseText;
                    if (bt.Text.Contains(keyword))
                    {
                        resultList.Add(bt);
                    }
                }
                else
                {
                    if (ex.SubPanels != null)
                    {
                        foreach (Expressions.SubPanel p in ex.SubPanels)
                        {
                            FindBaseTextInExpression(resultList, p, keyword);
                        }
                    }
                }
            }
        }

        /// <summary>
        /// 此方法仅仅只显示替换对话框。
        /// 具体的查找与替换则由对话框本身完成。
        /// </summary>
        public static void Replace()
        {
            ReplaceDialog replaceDialog = new ReplaceDialog() { Owner = Globals.MainWindow };
            replaceDialog.ShowDialog();
        }

        /// <summary>
        /// window 参数是为了恢复窗口焦点以启用快捷键。
        /// </summary>
        /// <param name="window"></param>
        public static void FindInDataBase(MainWindow window)
        {
            if (window == null) return;

            if (Globals.globalDataAdapter == null)
            {
                System.Windows.MessageBox.Show("发生意外错误，数据库适配器不存在！", Globals.appName,
                    MessageBoxButton.OK, MessageBoxImage.Warning);
                return;
            }

            InputWindow iw = new InputWindow(window, "请输入搜索关键词，以便在数据库中搜索：", "", Globals.appName) { Owner = Globals.MainWindow };
            if (iw.ShowDialog() != true)
            {
                window.Focus();
                return;
            }

            string keyWord = iw.InputedText;
            if (keyWord.Length <= 0) return;//如果文本过短。

            DataTable table = Globals.globalDataSetIn.Tables["Expressions"];
            table.Clear();

            string sqlWhereSubSentence = "";
            sqlWhereSubSentence = "(((Expressions.KeyWord) Like \"%" + keyWord + "%\")"
                            + " OR ((Expressions.ExpressionXml) Like \"%" + keyWord + "%\")"
                            + " OR ((Expressions.AuthorInfo) Like \"%" + keyWord + "%\")"
                           + " OR ((Expressions.Comment) Like \"%" + keyWord + "%\"))";

            //★★注意：在Access中通配符用“*”，而在Access的数据提供者中写SQL语句时，用“&”。

            OleDbDataAdapter oda1 = new OleDbDataAdapter("SELECT * FROM Expressions WHERE "
                + sqlWhereSubSentence + " ORDER BY ID",
                    "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + Globals.pathOfExpressionDatabase
                    + ";Jet OLEDB:Database Password=" + Globals.dataBaseKey);
            try
            {
                oda1.Fill(table);
            }
            finally
            {
                oda1.Dispose();
            }

            window.Focus();//重新启用快捷键。
            Globals.SwitchInputMethod(false);

            if (window.toolTab.SelectedItem != window.tiFindInDataBase)
            {
                window.toolTab.SelectedItem = window.tiFindInDataBase;
            }

            if (window.gcAssist.ActualWidth < 140)
            {
                window.gcAssist.Width = new GridLength(300);
                window.toolTab.Visibility = Visibility.Visible;
            }
        }
    }

    //改写了Find()方法。
    #region 此类已无必要。
    //public class FindTextBlock : TextBlock
    //{
    //    public FindTextBlock(Expressions.BaseText baseText)
    //    {
    //        if (base.Text != null)
    //        {
    //            if (baseText.Text.Length > 20)
    //            {
    //                this.Text = baseText.Text.Substring(0, 20) + "…";
    //            }
    //            else
    //            {
    //                this.Text = baseText.Text;
    //            }
    //        }
    //        else
    //        {
    //            this.Text = "<意外，无文本>";
    //        }

    //        this.BaseTextExID = baseText.ExID;

    //        this.ToolTip = "点击选取公式";
    //        this.MouseLeftButtonDown += new System.Windows.Input.MouseButtonEventHandler(FindTextBlock_MouseLeftButtonDown);
    //        this.MouseEnter += new System.Windows.Input.MouseEventHandler(FindTextBlock_MouseEnter);
    //        this.MouseLeave += new System.Windows.Input.MouseEventHandler(FindTextBlock_MouseLeave);
    //    }

    //    public string BaseTextExID { get; set; }

    //    void FindTextBlock_MouseLeave(object sender, System.Windows.Input.MouseEventArgs e)
    //    {
    //        this.Background = Brushes.Transparent;
    //    }

    //    void FindTextBlock_MouseEnter(object sender, System.Windows.Input.MouseEventArgs e)
    //    {
    //        this.Background = Brushes.LightGray;
    //    }

    //    void FindTextBlock_MouseLeftButtonDown(object sender, System.Windows.Input.MouseButtonEventArgs e)
    //    {
    //        Expressions.Expression ex = Globals.selectedEditor.GetExpressionByExID(
    //            Globals.selectedEditor.RootPanel, BaseTextExID);

    //        if (ex != null)
    //        {
    //            ex.Editor.SelectedExpression = ex;

    //            //可能被某个（或某些）折叠的标题文本隐藏了。
    //            if (ex.Visibility != Visibility.Visible)
    //            {
    //                //展开所有相关标题文本块。
    //                //只要找到前一个“可见的公式”，就必定是那个标题文本块。
    //                //然后，将这段索引区间的所有“标题文本块”全部展开即可。
    //                Expressions.Expression preVisibleEx = null;
    //                int curIndex = ex.ParentPanel.BasePanel.Children.IndexOf(ex);
    //                int preIndex = -1;
    //                for (int i = curIndex - 1; i >= 0; i--)
    //                {
    //                    Expressions.Expression iEx = ex.ParentPanel.BasePanel.Children[i] as Expressions.Expression;
    //                    if (iEx.Visibility == Visibility.Visible)
    //                    {
    //                        preVisibleEx = iEx;
    //                        preIndex = i;
    //                        break;
    //                    }
    //                }

    //                if (preVisibleEx != null && preIndex > -1)
    //                {
    //                    ModifingItem mi = new ModifingItem();

    //                    for (int i = preIndex; i < curIndex; i++)
    //                    {
    //                        Expressions.Expression iEx = ex.ParentPanel.BasePanel.Children[i] as Expressions.Expression;
    //                        if (iEx is Expressions.BaseText)
    //                        {
    //                            Expressions.BaseText iBt = iEx as Expressions.BaseText;
    //                            if (iBt.IsCollapsed)
    //                            {
    //                                List<Expressions.Expression> subIndentExpressions = iBt.GetSubIndentExpressions();
    //                                if (subIndentExpressions != null &&
    //                                    subIndentExpressions.Contains(ex))
    //                                {
    //                                    Action actUnCollapsed = new Action(iBt.ExID, -1,
    //                                        iBt.GetType().Name, "IsCollapsed",
    //                                        true.ToString(), false.ToString());

    //                                    iBt.IsCollapsed = false;

    //                                    mi.Add(actUnCollapsed);
    //                                }
    //                            }
    //                        }
    //                    }

    //                    if (mi.ModifiedPropertyAndValues.Count > 0)
    //                    {
    //                        ex.Editor.Do(mi);
    //                        ex.Editor.IsModified = true;
    //                    }
    //                }
    //            }

    //            //看看要不要选中。
    //            //if (ex.IsVisibleInScrollviewer == false)
    //            //{
    //            Command.AutoLocation(ex);
    //            //}
    //        }
    //        else
    //        {
    //            MessageBox.Show("无法选中对应文本块！在上次搜索后您可能将该文本块删除了，或者您可能将该文本块嵌入到其它公式中了。请重新搜索！",
    //                Globals.appName, MessageBoxButton.OK, MessageBoxImage.Warning);
    //        }
    //    }
    //}
    #endregion
}
